package smartbooks.ui.manager;

import java.util.logging.Level;
import java.util.logging.Logger;
import smartbooks.exceptions.MyException;
import smartbooks.ui.SmartBooksUserSettings;
import smartbooks.ui.helper.UserHelper;
import smartbooks.ui.util.CommonConstants;
import smartbooksdb.exception.MandatoryFieldException;
import smartbooksdb.exception.UserException;
import smartbooksdb.exception.UserOrganizationMappingException;
import smartbooksdb.hibernatebean.User;
import smartbooksdb.hibernatebean.UserOrganizationMapping;
import smartbooksdb.service.UserOrganizationMappingService;
import smartbooksdb.service.UserService;

/**
 *
 * @author Ankit
 */
public class UserManager implements CommonConstants {
    
    /**
     * It returns the total no of admins in the db
     * @return no of admin
     */
    public static int getNoOfAdmin() {
        int noOfAdmin;
        
        UserService userService = new UserService();
        noOfAdmin = (int)userService.getNumberOfAdmin();
        
        System.out.println("admin - "+noOfAdmin);
        
        return noOfAdmin;
    }
    
    /**
     * This method is used to create user
     * @param user
     * @param cpassword
     * @return 'true' if the user is created or else 'false'
     * @throws MyException
     * @throws MandatoryFieldException
     */
    public static boolean createUser(User user, char[] cpassword) throws MyException, MandatoryFieldException {
        try {
            System.out.println(user.toString());
            UserService userService = new UserService();
            
            boolean userPanelValidated = UserHelper.validateUser(user, cpassword);

            if(!userService.isUsernameAvailable(user.getUsername(), true)) {
                throw new MyException(USERNAME, "Username unavailable.");
            }
            
            if(userPanelValidated) {
                long userId = userService.createUser(user);
                
                if(SmartBooksUserSettings.USER_ID==0) {
                    SmartBooksUserSettings.USER_ID = userId;
                    SmartBooksUserSettings.USERNAME = user.getUsername();
                    SmartBooksUserSettings.USER_ROLE = user.getRole();
                }
                
                if(SmartBooksUserSettings.DEFAULT_ORG_ID!=0) {
                    UserManager.setDefaultOrgId(user.getUsername(), SmartBooksUserSettings.DEFAULT_ORG_ID);
                    
                    UserOrganizationMapping uom = new UserOrganizationMapping();
                    uom.setUserId(userId);
                    uom.setOrgId(SmartBooksUserSettings.DEFAULT_ORG_ID);
                    uom.setUpdatedBy(SmartBooksUserSettings.USERNAME);
                    UserOrganizationMappingService uomService = new UserOrganizationMappingService();
                    uomService.createUserOrganizationMapping(uom);
                }
                
                return true;
            }
        } catch (UserException | UserOrganizationMappingException ex) {
            Logger.getLogger(UserManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return false;
    }
    
    /**
     * This method is used to update user
     * @param user
     * @param cpassword
     * @param editUser
     * @return 'true' if the user is updated or else 'false'
     * @throws MyException
     * @throws MandatoryFieldException
     */
    public static boolean updateUser(User user, char[] cpassword, User editUser) throws MyException, MandatoryFieldException {
        try {
            System.out.println(user.toString());
            UserService userService = new UserService();
            
            boolean userPanelValidated = UserHelper.validateUser(user, cpassword);

            if(!user.getUsername().equals(editUser.getUsername())) {
                if(!userService.isUsernameAvailable(user.getUsername(), true)) {
                    throw new MyException(USERNAME, "Username unavailable.");
                }
            }
            
            if(userPanelValidated) {
                userService.updateUser(user);
                
                return true;
            }
        } catch (UserException ex) {
            Logger.getLogger(UserManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return false;
    }
    
    /**
     * This method is used to set the default org id for the username
     * @param username
     * @param orgId
     * @throws UserException
     * @throws MandatoryFieldException
     */
    public static void setDefaultOrgId(String username, Long orgId) throws UserException, MandatoryFieldException {
        UserService userService = new UserService();
        userService.setDefaultOrgId(username, orgId);
    }
    
    /**
     * This method is used to get the default organization id and its corresponding organization name
     * @param username
     * @return
     * @throws MandatoryFieldException
     */
    public static Object[] getDefaultOrganizationIdAndName(String username) throws MandatoryFieldException {
        Object[] defaultOrgIdAndName;
        
        UserService userService = new UserService();
        defaultOrgIdAndName = userService.getDefaultOrganizationIdAndName(username);
        
        return defaultOrgIdAndName;
    }
    
    /**
     * This method is used to get the user firstname using username
     * @param username
     * @return firstname
     */
    public static String getFirstnameByUsername(String username) {
        try {
            User user;
            
            UserService userService = new UserService();
            user = userService.getActiveUserByUsername(username);
            
            return user.getFirstName();
        } catch (MandatoryFieldException ex) {
            Logger.getLogger(UserManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }
}